package com.android.logcat.view;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.logcat.LoggerLevel;
import com.android.logcat.R;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GYL
 * @version 1.0
 * @dateTime 2020/7/1-17:52
 * @description
 */
public class LogViewrListAdapter extends BaseAdapter {
  private Context mContext;
  private List<String[]> mLoggerList=new ArrayList<>();
  private LayoutInflater mInflater;
  
  public LogViewrListAdapter(Context context){
    mContext=context;
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }
  
  public void add(@LoggerLevel String logLevel,String logger){
    this.mLoggerList.add(new String[]{logLevel,logger});
    notifyDataSetChanged();
  }
  
  @Override
  public int getCount() {
    return mLoggerList.size();
  }
  
  @Override
  public String[] getItem(int position) {
    return mLoggerList.get(position);
  }
  
  @Override
  public long getItemId(int position) {
    return position;
  }
  
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    TextView holder;
    String[] logcatEntry = getItem(position);
    if (convertView == null) {
      convertView = mInflater.inflate(R.layout.list_logger_item, parent, false);
      holder = (TextView) convertView.findViewById(R.id.logEntry);
      holder.setTypeface(Typeface.MONOSPACE);
      convertView.setTag(holder);
    } else {
      holder = (TextView) convertView.getTag();
    }
    holder.setText(logcatEntry[1]);
    switch (logcatEntry[0]){
      case LoggerLevel.DEBUG:
        holder.setTextColor(0xff0f9d58);
        break;
      case LoggerLevel.SYSTEMOUT:
      case LoggerLevel.INFO:
        holder.setTextColor(0xff4285f4);
        break;
      case LoggerLevel.VERBOSE:
        holder.setTextColor(0xffcccccc);
        break;
      case LoggerLevel.WARM:
        holder.setTextColor(0xffff9800);
        break;
      case LoggerLevel.WTF:
      case LoggerLevel.ERROR:
        holder.setTextColor(0xffb93221);
        break;
        default:break;
    }
    final boolean autoscroll = (parent.getScrollY() + parent.getHeight() >= parent.getBottom());
    if (autoscroll) {
      ((ListView) parent).setSelection(getCount() - 1);
    }
    return convertView;
  }
  
  public void clear() {
    mLoggerList.clear();
    notifyDataSetChanged();
  }
}
